package com.baidu.service.impl;

import com.baidu.common.bean.Goods;
import com.baidu.common.bean.GoodsType;
import com.baidu.common.exception.WebException;
import com.baidu.dao.GoodsDao;
import com.baidu.dao.TypeDao;
import com.baidu.dao.impl.GoodsDaoImpl;
import com.baidu.dao.impl.TypeDaoImpl;
import com.baidu.dao.util.JdbcUtil;
import com.baidu.service.GoodsService;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @Author: BSS
 * @create: 2020/8/20/9:24
 */
public class GoodsServiceImpl implements GoodsService {
    private GoodsDao goodsDao = new GoodsDaoImpl();
    private Connection connection = JdbcUtil.getConnection();
    private TypeDao typeDao = new TypeDaoImpl();
    public GoodsServiceImpl() throws WebException {}

    @Override
    public Goods get(Integer id) throws WebException {
        return goodsDao.get(id);
    }

    @Override
    public int update(Goods goods) throws WebException {
        try {
            GoodsType type = goods.getGoodsType();
            GoodsType dbGoodsType = typeDao.getTypeByName(type.getName());
            goods.setGoodsType(dbGoodsType);
            int isSuccess = goodsDao.update(goods);
            connection.commit();
            return isSuccess;
        } catch (WebException | SQLException e) {
            e.printStackTrace();
            try {
                connection.rollback();
                throw new WebException(e.getMessage());
            } catch (SQLException ex) {
                ex.printStackTrace();
                throw new WebException(ex.getMessage());
            }
        }
    }

    @Override
    public int delete(Integer id) throws WebException {
        try {
            int isSuccess = goodsDao.delete(id);
            connection.commit();
            return isSuccess;
        } catch (WebException  | SQLException e) {
            e.printStackTrace();
            try {
                connection.rollback();
                throw new WebException(e.getMessage());
            } catch (SQLException ex) {
                ex.printStackTrace();
                throw new WebException(ex.getMessage());
            }
        }
    }

    @Override
    public int add(Goods goods) throws WebException {
        GoodsType type = goods.getGoodsType();
        GoodsType daGoodsType = typeDao.getTypeByName(type.getName());
        try {
            goods.setGoodsType(daGoodsType);
            return goodsDao.add(goods);
        } catch (WebException e) {
            e.printStackTrace();
            throw new WebException("添加商品时异常！");
        }

    }

    @Override
    public List<Goods> queryGoodsTypeList() throws WebException {
        return goodsDao.queryGoodsTypeList();
    }
}
